package com.yanjiali.controller;

import com.yanjiali.dto.respdto.QianFanResponseBean;
import com.yanjiali.service.impl.GptQianFanServiceImpl;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import javax.annotation.Resource;


/**
 * 千帆接口调用
 */
@RestController
public class QianFanController {

    //用于流式请求第三方的实现类
    @Resource
    GptQianFanServiceImpl qianFanService;

    //通过stream返回流式数据
    @GetMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<QianFanResponseBean>> getChat(@RequestParam("content")String content) {
        //实现类发送消息并获取返回结果
        return qianFanService.doQianFanStream(content)
                //映射返回结果，再返回给前端
                .map(aiAnswerDTO -> ServerSentEvent.<QianFanResponseBean>builder()
                        .data(aiAnswerDTO)
                        .build()
                )
                //发生异常时发送空对象
                .onErrorResume(e -> Flux.empty());
    }
}
